#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <amqp.h>
#include <amqp_tcp_socket.h>

#include <assert.h>

#include "utils.h"

int main(int argc, char const *const *argv)
{
  // char const *hostname;
  char hostname[128] = "localhost";
  int port = 5672;
  int status;
  amqp_socket_t *socket = NULL;
  amqp_connection_state_t conn;

  conn = amqp_new_connection();

  socket = amqp_tcp_socket_new(conn);
  if (!socket)
  {
    die("creating TCP socket");
  }

  status = amqp_socket_open(socket, hostname, port);
  if (status)
  {
    die("opening TCP socket");
  }

  die_on_amqp_error(amqp_login(conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN,
                               "admin", "admin"),
                    "Logging in");
  amqp_channel_open(conn, 1);
  die_on_amqp_error(amqp_get_rpc_reply(conn), "Opening channel");

  // 声明交换机
//   amqp_bytes_t exchange = amqp_cstring_bytes("direct-exchange");
//   amqp_bytes_t exchangetype = amqp_cstring_bytes("direct");
//   amqp_exchange_declare(conn, 1, exchange, exchangetype, 0, 1, 0, 0, amqp_empty_table);
//   die_on_amqp_error(amqp_get_rpc_reply(conn), "Declaring exchange");

  // 声明消息队列
  amqp_bytes_t queuename = amqp_cstring_bytes("slave-health-mem");
  amqp_queue_declare_ok_t *r = amqp_queue_declare(conn, 1, queuename, 0, 1, 0, 0, amqp_empty_table);
  die_on_amqp_error(amqp_get_rpc_reply(conn), "Declaring queue");
  printf("%d message on queue\n", r->message_count);
  // bind
//   amqp_bytes_t amqroutingkey = amqp_cstring_bytes("test");
//   amqp_queue_bind(conn, 1, queuename, exchange, amqroutingkey, amqp_empty_table);
//   die_on_amqp_error(amqp_get_rpc_reply(conn), "Unbinding");

  // publish message
//   amqp_basic_properties_t props;
//   props._flags = AMQP_BASIC_CONTENT_TYPE_FLAG | AMQP_BASIC_DELIVERY_MODE_FLAG;
//   props.content_type = amqp_cstring_bytes("text/plain");
//   props.delivery_mode = 2; /* persistent delivery mode */
//   die_on_error(amqp_basic_publish(conn, 1, exchange, amqroutingkey, 0, 0, &props, amqp_cstring_bytes("hello world")),
//                "Publishing");
  
  // end
  die_on_amqp_error(amqp_channel_close(conn, 1, AMQP_REPLY_SUCCESS),
                    "Closing channel");
  die_on_amqp_error(amqp_connection_close(conn, AMQP_REPLY_SUCCESS),
                    "Closing connection");
  die_on_error(amqp_destroy_connection(conn), "Ending connection");

  return 0;
}